package cn.wolfcode.rbac.service.system_manage.impl;


import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.system_manage.EmployeeMapper;
import cn.wolfcode.rbac.mapper.system_manage.PermissionMapper;
import cn.wolfcode.rbac.query.QueryEm;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.system_manage.IEmployeeService;
import cn.wolfcode.rbac.util.CurrentUtil;
import cn.wolfcode.rbac.util.LoginException;
import cn.wolfcode.rbac.util.PageResult;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @version 1.0
 * @Author:Cao Zhijian
 * @DATE:2020/12/24 0024 14:40:32
 */

@Service
public class IEmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);

        // 删除关系表中的关系
        employeeMapper.deleteRoleAndEmployeeRelation(id);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

//    @Override
//    public PageResult query(QueryObject queryObject) {
//
//        int count = employeeMapper.selectForCount();
//
//        if(count == 0){
//            // 1.如果数据库中没有数据是不需要分页显示，直接返回一个空数据
//            return new PageResult(1,3,Collections.emptyList(),0);
//        }else {
//            // 2.如果数据库中有数据就要分页显示
//            List<Employee> employees = employeeMapper.selectForList(queryObject);
//            return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),employees,count);
//        }
//    }

    @Override
    public void login(String username, String password) {
//        System.out.println(username);
//        System.out.println("");
//        System.out.println("");
        Employee e = employeeMapper.selectByusernameAndpassword(username,password);
//        System.out.println(e.toString());
//        System.out.println("");
//        System.out.println("");
        if( e == null){
            throw new LoginException("账号或密码不正确");
        }else {
            // 将e存入session中
            CurrentUtil.setCurrent(e);

            // 把用户所拥有的的权限加入session中
            // 利用set集合进行去重
            Set<String> expressions = permissionMapper.selectExpressionsByEmployeeId(e.getId());
            CurrentUtil.setExpression(expressions);
        }
    }

    @Override
    public void saveOrUpdate(Employee employee,Long[] ids) {
        if(employee.getId() == null){
            employeeMapper.insert(employee);
        }else {
            employeeMapper.updateByPrimaryKey(employee);
            employeeMapper.deleteRoleAndEmployeeRelation(employee.getId());
        }

        if(ids != null && ids.length > 0){
            for(Long roleId : ids){
                employeeMapper.insertRoleAndEmployeeRelation(employee.getId(),roleId);
            }
        }
    }

    //---------------------



    @Override
    public void exportXls() {
        String filePath = "D:/txt/";
        String fileName = java.util.UUID.randomUUID().toString().replaceAll("-", "")+".xlsx";
        File pathFile = new File(filePath);
        if(!pathFile.exists()){
            pathFile.mkdir();
        }
        String relFilePath = filePath + File.separator + fileName;
        File file = new File(relFilePath);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {

            XSSFWorkbook wb1 = new XSSFWorkbook();
            FileOutputStream os = new FileOutputStream(relFilePath);
            wb1.createSheet("test");// 创建第一张工作簿
            wb1.write(os);
            os.close();
            wb1.close();
//            Workbook wb2 = WorkbookFactory.create(new FileInputStream(file));
            XSSFWorkbook wb2 = new XSSFWorkbook(new FileInputStream(relFilePath));
            SXSSFWorkbook swb = new SXSSFWorkbook(wb2, 100);
            SXSSFSheet sh = swb.getSheetAt(0);// 获取第一张工作簿
            Row row = sh.createRow(0);
            row.createCell(0).setCellValue("姓名");
            row.createCell(1).setCellValue("邮箱");
            row.createCell(2).setCellValue("年龄");
            List<Employee> employees = this.employeeMapper.selectAll();

            for(int i = 0; i < employees.size(); i++) {
                row = sh.createRow(i+1);
                Employee employee = (Employee)employees.get(i);
                System.out.println(employee);
                row.createCell(0).setCellValue(employee.getName());
                row.createCell(1).setCellValue(employee.getEmail());
                row.createCell(2).setCellValue((double)employee.getAge().intValue());
            }
            FileOutputStream os1 = new FileOutputStream(file);
            swb.write(os1);
            os1.close();
            swb.close();





        } catch (IOException e) {
            e.printStackTrace();

        }


    }






    @Override
    public void importXls(MultipartFile file) throws Exception {
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        Sheet sheet = wb.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();

        for(int i = 1; i <= lastRowNum; ++i) {
            Row row = sheet.getRow(i);
            Employee employee = new Employee();

            employee.setName(row.getCell(0).getStringCellValue());
            employee.setPassword(String.valueOf((int)row.getCell(1).getNumericCellValue()));
            employee.setEmail(row.getCell(2).getStringCellValue());
            employee.setAge((int)row.getCell(3).getNumericCellValue());

            System.out.println(row.getCell(0).getStringCellValue());
            System.out.println(row.getCell(2).getStringCellValue());
            System.out.println(String.valueOf((int)row.getCell(1).getNumericCellValue()));
            System.out.println((int)row.getCell(3).getNumericCellValue());


            this.save(employee, (Long[])null);
        }

    }

    @Override
    public List<Department> listAllDepartment(){
        return employeeMapper.getAllDepartment();
    }
    @Override
    public List<Employee> selectEmLs(String... param){
        return this.employeeMapper.selectEmList(param);
    }

    @Override
    public void batchDelete(Long[] ids) {
        this.employeeMapper.deleteBatch(ids);
    }

    @Override
    public void save(Employee employee, Long[] ids) {

        this.employeeMapper.insert(employee);
        if (ids != null && ids.length > 0) {
            Long[] var5 = ids;
            int var6 = ids.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                Long rid = var5[var7];
                this.employeeMapper.insertRelation(employee.getId(), rid);
            }
        }

    }

    @Override
    public PageResult query(QueryEm queryEm) {

        int count = employeeMapper.selectForCount();

        if(count == 0){
            // 1.如果数据库中没有数据是不需要分页显示，直接返回一个空数据
            return new PageResult(1,3,Collections.emptyList(),0);
        }else {
            // 2.如果数据库中有数据就要分页显示
            List<Employee> employees = employeeMapper.selectForList2(queryEm);
            return new PageResult(queryEm.getCurrentPage(),queryEm.getPageSize(),employees,count);//queryEm.getPageSize()
        }
    }
}
